/*********************************************************************************
 *      Copyright:  (C) 2022 zengwen<1825984037@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  socket_server_init.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(07/07/22)
 *         Author:  zengwen <1825984037@qq.com>
 *      ChangeLog:  1, Release initial version on "07/07/22 19:04:25"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "logger.h"



//初始化socket

int socket_sever_init(char *listen_ip,int listen_port)
{
	struct sockaddr_in   servaddr;
	int                  rv=0;
	int                  on=1;
	int                  listenfd;

	if((listenfd=socket(AF_INET,SOCK_STREAM,0))<0)
	{
		log_err("Create TCP socket failure:%s\n",strerror(errno));
		return -1;
	}
	log_info("Create TCP socket listenfd=%d sucessfuly!\n",listenfd);

	//允许fd在bind过程中本地地址可重复使用
	setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
	memset(&servaddr,0,sizeof(servaddr));
	servaddr.sin_family=AF_INET;
	servaddr.sin_port=htons(listen_port);

	if(!listen_ip)
	{
		servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
	}
	else
	{
		if(inet_pton(AF_INET,listen_ip,&servaddr.sin_addr)<=0)
		{
			log_err("inet_pton() set listen IP address failure\n");
			rv=-2;
			goto cleanup;
		}
	}
	printf ("Waiting for client connet...\n");

	if(bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr))<0)
	{
		printf("Bind to TCP socket failure:%s\n",strerror(errno));
		rv=-3;
		goto cleanup;
	}
	log_info("Bind to TCP socket sucessfully!\n");

	if(listen(listenfd,13)<0)
	{
		log_err("Listen to the TCP socket failure:%s\n",strerror(errno));
		rv=-4;
		goto cleanup;
	}
	log_info("Listen to TCP socket sucessfully!\n");

cleanup:
	if(rv<0)
	{
		close(listenfd);
	}
	else
		rv=listenfd;
	return rv;
}
